import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import { NotificationType, NotificationStatus, NotificationLevel } from '../src/types/api/notification'
import type { 
  Notification, 
  NotificationQuery,
  NotificationList
} from '../src/types/api/notification'
import type { API } from '../src/types/api/response'

const Random = Mock.Random

// ------------ 常量定义 ------------
const notificationTypes = [
  { value: NotificationType.SYSTEM, label: '系统通知' },
  { value: NotificationType.MESSAGE, label: '消息通知' },
  { value: NotificationType.TASK, label: '任务通知' },
  { value: NotificationType.TODO, label: '待办事项' }
]

const notificationStatuses = [
  { value: NotificationStatus.UNREAD, label: '未读' },
  { value: NotificationStatus.READ, label: '已读' }
]

const notificationLevels = [
  { value: NotificationLevel.NORMAL, label: '普通' },
  { value: NotificationLevel.IMPORTANT, label: '重要' },
  { value: NotificationLevel.URGENT, label: '紧急' }
]

// ------------ 工具函数 ------------
/**
 * 按通知类型生成符合真实场景的标题
 */
const generateTitleByType = (type: NotificationType): string => {
  switch (type) {
    case NotificationType.SYSTEM:
      return Random.pick([
        '系统维护通知',
        '新功能上线公告',
        '系统升级提示',
        '安全更新提醒',
        '账号安全提醒',
        '系统性能优化完成',
        '数据备份通知'
      ])
    case NotificationType.MESSAGE:
      return Random.pick([
        '新消息提醒',
        '会议通知',
        '信息更新',
        '团队公告',
        '活动邀请',
        '订单状态更新',
        '客户反馈回复'
      ])
    case NotificationType.TASK:
      return Random.pick([
        '任务分配通知',
        '项目截止日提醒',
        '任务状态更新',
        '协作任务邀请',
        '项目进度提醒',
        '文档更新通知',
        '代码审核请求'
      ])
    case NotificationType.TODO:
      return Random.pick([
        '待办事项提醒',
        '审批申请待处理',
        '待确认事项',
        '日程安排提醒',
        '待回复信息',
        '待提交报告',
        '即将到期提醒'
      ])
    default:
      return Random.ctitle(5, 15)
  }
}

/**
 * 按通知类型生成符合真实场景的内容
 */
const generateContentByType = (type: NotificationType): string => {
  switch (type) {
    case NotificationType.SYSTEM:
      return Random.pick([
        `系统将于${Random.date('yyyy-MM-dd')}${Random.time('HH:mm')}至${Random.time('HH:mm')}进行升级维护，期间系统将暂停服务，请提前做好准备。`,
        `新版本${Random.increment(10)}已发布，新增${Random.cword(3, 8)}等功能，修复了已知问题，欢迎体验。`,
        `您的账号在${Random.date('yyyy-MM-dd')}${Random.time('HH:mm:ss')}有异地登录记录，请确认是否为本人操作。`,
        `系统性能优化完成，访问速度提升${Random.integer(20, 50)}%，欢迎体验。`
      ])
    case NotificationType.MESSAGE:
      return Random.pick([
        `您有${Random.integer(1, 5)}条新消息待查看，请尽快处理。`,
        `${Random.cname()}邀请您参加${Random.date('MM月dd日')}${Random.time('HH:mm')}的${Random.cword(2, 5)}会议。`,
        `订单#${Random.string('upper', 3)}${Random.string('number', 6)}状态已更新为${Random.pick(['已发货', '已签收', '处理中', '已完成'])}。`,
        `客户"${Random.cword(2, 4)}${Random.pick(['公司', '集团', '企业'])}"对您的服务评价为${Random.integer(4, 5)}星。`
      ])
    case NotificationType.TASK:
      return Random.pick([
        `${Random.cname()}为您分配了"${Random.cword(3, 8)}"任务，请在${Random.date('yyyy-MM-dd')}前完成。`,
        `项目"${Random.cword(3, 8)}"即将在${Random.date('yyyy-MM-dd')}截止，当前完成度${Random.integer(60, 90)}%。`,
        `您负责的"${Random.cword(3, 8)}"任务状态已更新为${Random.pick(['进行中', '待审核', '已完成'])}。`,
        `${Random.cname()}邀请您协作处理"${Random.cword(3, 8)}"任务。`
      ])
    case NotificationType.TODO:
      return Random.pick([
        `您有一项"${Random.cword(3, 8)}"待办事项需要处理。`,
        `员工"${Random.cname()}"的${Random.pick(['请假', '加班', '报销', '采购'])}申请待您审批。`,
        `请在${Random.date('yyyy-MM-dd')}前提交${Random.cword(3, 8)}报告。`,
        `您有${Random.integer(1, 5)}项待办事项即将到期，请尽快处理。`
      ])
    default:
      return Random.cparagraph(1, 2)
  }
}

/**
 * 按通知类型生成符合真实场景的发送者信息
 */
const generateSenderByType = (type: NotificationType): { id: string, name: string } => {
  switch (type) {
    case NotificationType.SYSTEM:
      return {
        id: Random.pick(['system', 'admin', 'security', 'monitor']),
        name: Random.pick(['系统管理员', '系统通知', '安全中心', '监控系统', '运维团队'])
      }
    case NotificationType.MESSAGE:
      return {
        id: Random.pick(['notification', Random.id(), 'crm', 'marketing']),
        name: Random.pick([Random.cname(), '消息中心', '客户关系', '市场部门'])
      }
    case NotificationType.TASK:
      return {
        id: Random.pick(['project', 'task', Random.id()]),
        name: Random.pick([Random.cname(), '项目管理系统', '任务中心'])
      }
    case NotificationType.TODO:
      return {
        id: Random.pick(['workflow', 'approval', Random.id()]),
        name: Random.pick(['工作流系统', '审批系统', Random.cname()])
      }
    default:
      return {
        id: Random.id(),
        name: Random.cname()
      }
  }
}

/**
 * 按通知类型生成符合真实场景的链接
 */
const generateLinkByType = (type: NotificationType): string | undefined => {
  switch (type) {
    case NotificationType.SYSTEM:
      return Random.pick([
        '/system/notice',
        '/system/version',
        '/user/security',
        '/system/settings',
        undefined
      ])
    case NotificationType.MESSAGE:
      return Random.pick([
        '/message/detail',
        '/chat',
        '/mail/inbox',
        '/order/detail',
        undefined
      ])
    case NotificationType.TASK:
      return Random.pick([
        '/task/detail',
        '/project/progress',
        '/document/edit',
        '/code/review',
        undefined
      ])
    case NotificationType.TODO:
      return Random.pick([
        '/approval/waiting',
        '/todo/list',
        '/report/submit',
        '/schedule/calendar',
        undefined
      ])
    default:
      return undefined
  }
}

/**
 * 按通知类型生成符合真实场景的额外数据
 */
const generateExtraDataByType = (type: NotificationType): string | undefined => {
  switch (type) {
    case NotificationType.SYSTEM:
      return Random.pick([
        undefined,
        JSON.stringify({
          version: `v${Random.float(1, 10, 1, 2)}`,
          features: ['功能1', '功能2', '功能3'],
          requireRestart: Random.boolean()
        }),
        JSON.stringify({
          ipAddress: `${Random.integer(1, 255)}.${Random.integer(1, 255)}.${Random.integer(1, 255)}.${Random.integer(1, 255)}`,
          device: Random.pick(['Windows PC', 'MacBook', 'iPhone', 'Android']),
          location: Random.city()
        })
      ])
    case NotificationType.MESSAGE:
      return Random.pick([
        undefined,
        JSON.stringify({
          messageId: Random.guid(),
          chatId: Random.guid(),
          unreadCount: Random.integer(1, 10)
        }),
        JSON.stringify({
          meetingId: `M${Random.datetime('yyyyMMddHHmm')}`,
          location: Random.pick(['会议室1', '会议室2', '线上会议']),
          participants: Random.integer(2, 10)
        })
      ])
    case NotificationType.TASK:
      return Random.pick([
        undefined,
        JSON.stringify({
          taskId: `T${Random.string('number', 6)}`,
          projectId: `P${Random.string('number', 6)}`,
          deadline: Random.datetime('yyyy-MM-dd HH:mm:ss'),
          priority: Random.pick(['low', 'medium', 'high'])
        }),
        JSON.stringify({
          documentId: `D${Random.string('number', 6)}`,
          version: Random.float(1, 5, 1, 1),
          permission: Random.pick(['read', 'write', 'admin'])
        })
      ])
    case NotificationType.TODO:
      return Random.pick([
        undefined,
        JSON.stringify({
          todoId: `TD${Random.string('number', 6)}`,
          status: Random.pick(['pending', 'overdue', 'completed']),
          reminderTime: Random.datetime('yyyy-MM-dd HH:mm:ss')
        }),
        JSON.stringify({
          formId: `F${Random.string('number', 6)}`,
          formType: Random.pick(['leave', 'expense', 'purchase']),
          applicant: Random.cname(),
          amount: Random.float(100, 10000, 0, 2).toString()
        })
      ])
    default:
      return undefined
  }
}

/**
 * 生成更加真实的随机通知
 */
const generateRealisticNotification = (id: string): Notification => {
  const type = notificationTypes[Math.floor(Math.random() * notificationTypes.length)].value
  const level = notificationLevels[Math.floor(Math.random() * notificationLevels.length)].value
  const status = notificationStatuses[Math.floor(Math.random() * notificationStatuses.length)].value
  const createTime = Random.datetime('yyyy-MM-dd HH:mm:ss')
  const readTime = status === NotificationStatus.READ ? Random.datetime('yyyy-MM-dd HH:mm:ss') : undefined
  const sender = generateSenderByType(type)

  return {
    id,
    title: generateTitleByType(type),
    content: generateContentByType(type),
    type,
    level,
    status,
    targetUserId: Random.pick(['all', 'user_001', 'user_002', Random.id()]),
    senderId: sender.id,
    senderName: sender.name,
    createTime,
    readTime,
    link: generateLinkByType(type),
    extraData: generateExtraDataByType(type)
  }
}

// ------------ 模拟数据 ------------
// 直接使用生成函数创建模拟数据
const notifications: Notification[] = Array.from(
  { length: 100 }, 
  (_, index) => generateRealisticNotification(String(index + 1))
)

// ------------ API 实现 ------------
/**
 * 获取通知列表
 */
const getNotificationListApi: MockMethod = {
  url: '/api/notification/list',
  method: 'get',
  response: ({ query }: { query: NotificationQuery }): API.Response<NotificationList> => {
    const { title: keyword, type, status, page = 1, pageSize = 10 } = query
    
    // 确保 page 和 pageSize 是数字类型
    const pageNum = Number(page)
    const pageSizeNum = Number(pageSize)
    
    let filteredNotifications = [...notifications]

    if (keyword) {
      filteredNotifications = filteredNotifications.filter(
        notification => notification.title.includes(keyword) || notification.content.includes(keyword)
      )
    }

    if (type) {
      filteredNotifications = filteredNotifications.filter(notification => notification.type === type)
    }

    if (status) {
      filteredNotifications = filteredNotifications.filter(notification => notification.status === status)
    }

    const startIndex = (pageNum - 1) * pageSizeNum
    const endIndex = startIndex + pageSizeNum
    const list = filteredNotifications.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredNotifications.length
      }
    }
  }
}

/**
 * 获取通知详情
 */
const getNotificationDetailApi: MockMethod = {
  url: '/api/notification/:id',
  method: 'get',
  response: ({ params }: { params?: { id?: string } }): API.Response<Notification | null> => {
    if (!params || !params.id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误：缺少通知ID',
        data: null
      }
    }
    
    const notification = notifications.find(item => item.id === params.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: notification || null
    }
  }
}

/**
 * 标记通知为已读
 */
const markNotificationReadApi: MockMethod = {
  url: '/api/notification/:id/read',
  method: 'put',
  response: ({ query, url }: { query: { id?: string }, url: string }): API.Response<null> => {
    // 增强参数处理，从URL中提取ID
    let notificationId = query.id;
    
    // 如果params中没有id，尝试从URL中提取
    if (!notificationId && url) {
      const matches = url.match(/\/api\/notification\/([^\/]+)\/read/);
      if (matches && matches[1]) {
        notificationId = matches[1];
      }
    }
    
    // 检查是否有ID
    if (!notificationId) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误：缺少通知ID',
        data: null
      }
    }
    
    const notification = notifications.find(item => item.id === notificationId)
    if (notification) {
      notification.status = NotificationStatus.READ
      notification.readTime = new Date().toISOString()
    }
    return {
      code: 200,
      success: true,
      message: '标记成功',
      data: null
    }
  }
}

/**
 * 批量标记通知为已读
 */
const batchMarkNotificationReadApi: MockMethod = {
  url: '/api/notification/read',
  method: 'put',
  response: ({ body }: { body?: { ids?: string[] } }): API.Response<null> => {
    if (!body || !body.ids || !Array.isArray(body.ids) || body.ids.length === 0) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误：缺少通知ID列表',
        data: null
      }
    }
    
    const { ids = [] } = body
    ids.forEach(id => {
      if (id) {
        const notification = notifications.find(item => item.id === id)
        if (notification) {
          notification.status = NotificationStatus.READ
          notification.readTime = new Date().toISOString()
        }
      }
    })
    return {
      code: 200,
      success: true,
      message: '标记成功',
      data: null
    }
  }
}

/**
 * 标记所有通知为已读
 */
const markAllNotificationsReadApi: MockMethod = {
  url: '/api/notification/read-all',
  method: 'put',
  response: (): API.Response<null> => {
    notifications.forEach(notification => {
      if (notification.status === NotificationStatus.UNREAD) {
        notification.status = NotificationStatus.READ
        notification.readTime = new Date().toISOString()
      }
    })
    return {
      code: 200,
      success: true,
      message: '全部标记为已读',
      data: null
    }
  }
}

/**
 * 清空所有已读通知
 */
const clearReadNotificationsApi: MockMethod = {
  url: '/api/notification/clear-read',
  method: 'delete',
  response: (): API.Response<null> => {
    // 找出所有已读通知的索引
    for (let i = notifications.length - 1; i >= 0; i--) {
      if (notifications[i].status === NotificationStatus.READ) {
        notifications.splice(i, 1)
      }
    }
    return {
      code: 200,
      success: true,
      message: '已清空所有已读通知',
      data: null
    }
  }
}

/**
 * 获取通知统计数据
 */
const getNotificationStatsApi: MockMethod = {
  url: '/api/notification/stats',
  method: 'get',
  response: (): API.Response<{
    unreadCount: number;
    readCount: number;
    totalCount: number;
  }> => {
    const unreadCount = notifications.filter(n => n.status === NotificationStatus.UNREAD).length
    const readCount = notifications.filter(n => n.status === NotificationStatus.READ).length
    
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        unreadCount,
        readCount,
        totalCount: notifications.length
      }
    }
  }
}

/**
 * 删除通知
 */
const deleteNotificationApi: MockMethod = {
  url: '/api/notification/:id',
  method: 'delete',
  response: ({ query }: { query: { id: string } }): API.Response<null> => {
    if (!query || !query.id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误：缺少通知ID',
        data: null
      }
    }
    
    const index = notifications.findIndex(item => item.id === query.id)
    if (index > -1) {
      notifications.splice(index, 1)
    }
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 批量删除通知
 */
const batchDeleteNotificationApi: MockMethod = {
  url: '/api/notification',
  method: 'delete',
  response: ({ body }: { body?: { ids?: string[] } }): API.Response<null> => {
    if (!body || !body.ids || !Array.isArray(body.ids) || body.ids.length === 0) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误：缺少通知ID列表',
        data: null
      }
    }
    
    const { ids = [] } = body
    ids.forEach(id => {
      if (id) {
        const index = notifications.findIndex(item => item.id === id)
        if (index > -1) {
          notifications.splice(index, 1)
        }
      }
    })
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

// ------------ 导出 ------------
export default [
  getNotificationListApi,
  getNotificationDetailApi,
  markNotificationReadApi,
  batchMarkNotificationReadApi,
  markAllNotificationsReadApi,
  clearReadNotificationsApi,
  getNotificationStatsApi,
  deleteNotificationApi,
  batchDeleteNotificationApi
] as MockMethod[] 